package my.utils;

import java.awt.Color;
import java.awt.Font;
import java.awt.Graphics;
import java.awt.GraphicsConfiguration;
import java.awt.GraphicsDevice;
import java.awt.GraphicsEnvironment;
import java.awt.HeadlessException;
import java.awt.Image;
import java.awt.Rectangle;
import java.awt.Transparency;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
import java.util.Random;
import java.awt.Toolkit;
import javax.imageio.ImageIO;
import javax.swing.ImageIcon;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

public final class ImageUtil {
	private static Log log = LogFactory.getLog(ImageUtil.class);
	private static final int LINES = 10;// 干扰线数量
	private static final int POINT = 1000;// 噪点数量
	private static final int LENGTH = 4;// 产生的字符长度
	private static final int WIDTH = 140;// 宽度
	private static final int HEIGHT = 70;// 高度
	private static final int FONT_SIZE = 48;// 字体大小
	static Random r = new Random();
	
	public static void main(String[] args) throws IOException{
		Image img = Toolkit.getDefaultToolkit().getImage("C:\\google.jpg");
		BufferedImage bi_scale = toBufferedImage(img);
		ImageIO.write(bi_scale, "jpg",new File("C:\\2.jpg"));
	}

	/**
	 * 合并图片,将原图像合并到目标图像中.
	 * 
	 * @param srcImg
	 *            源图像
	 * @param destImg
	 *            目标图像,请传递BufferedImage类型
	 * @param rectangle
	 *            区域
	 * @return 合并后的目标图片
	 */
	public static Image mergeImage(Image srcImg, Image destImg, Rectangle rectangle) {
		destImg.getGraphics().drawImage(srcImg, rectangle.x, rectangle.y, rectangle.width, rectangle.height, null);
		destImg.flush();
		return destImg;
	}
	public static void saveImage(BufferedImage image,String savePath){
		try {
			ImageIO.write(image, "png", new File(savePath));
		} catch (IOException e) {
			log.error("保存图片失败...",e);
		}
		
	}
	/**
	 * @描述 将一个Image对象转换成BufferedImage
	 * @作者 钟诚
	 * @日期 2012-6-15
	 * @时间 下午04:36:02
	 * @param image
	 * @return
	 */
	public static BufferedImage toBufferedImage(Image image) {
		if (image instanceof BufferedImage) {
		    return (BufferedImage)image;
		 }

		// This code ensures that all the pixels in the image are loaded
		 image = new ImageIcon(image).getImage();

		// Determine if the image has transparent pixels; for this method's
		// implementation, see e661 Determining If an Image Has Transparent Pixels
		//boolean hasAlpha = hasAlpha(image);

		// Create a buffered image with a format that's compatible with the screen
		 BufferedImage bimage = null;
		 GraphicsEnvironment ge = GraphicsEnvironment.getLocalGraphicsEnvironment();
		try {
		    // Determine the type of transparency of the new buffered image
		    int transparency = Transparency.OPAQUE;
		   /* if (hasAlpha) {
			 transparency = Transparency.BITMASK;
		     }*/

		    // Create the buffered image
		     GraphicsDevice gs = ge.getDefaultScreenDevice();
		     GraphicsConfiguration gc = gs.getDefaultConfiguration();
		     bimage = gc.createCompatibleImage(
			 image.getWidth(null), image.getHeight(null), transparency);
		 } catch (HeadlessException e) {
		    // The system does not have a screen
		 }

		if (bimage == null) {
		    // Create a buffered image using the default color model
		    int type = BufferedImage.TYPE_INT_RGB;
		    //int type = BufferedImage.TYPE_3BYTE_BGR;//by wang
		    /*if (hasAlpha) {
			 type = BufferedImage.TYPE_INT_ARGB;
		     }*/
		     bimage = new BufferedImage(image.getWidth(null), image.getHeight(null), type);
		 }

		// Copy image to buffered image
		 Graphics g = bimage.createGraphics();

		// Paint the image onto the buffered image
		 g.drawImage(image, 0, 0, null);
		 g.dispose();

		return bimage;
	}
	/**
	 * 
	 * @描述 验证码
	 * @作者 钟诚
	 * @日期 2012-6-15
	 * @时间 下午04:39:19
	 * @return
	 */
	public static Map<String, BufferedImage> getImage() {
		StringBuffer sb = new StringBuffer();
		BufferedImage image = new BufferedImage(WIDTH, HEIGHT, BufferedImage.TYPE_INT_RGB);
		Graphics g = image.getGraphics();
		g.setColor(getRandomColorB());// 随机背景色128内
		// g.setColor(getRandomColor());//随机背景色
		Font font = new Font("Arial", Font.PLAIN, FONT_SIZE);// Comic Sans MS
		g.setFont(font);
		g.fillRect(0, 0, WIDTH, HEIGHT);
		// 画随机字符
		for (int i = 0; i < LENGTH; i++) {
			g.setColor(getRandomColorC());
			// 26个字母
			String str = "" + (char) (r.nextInt(26) + 65);
			// 随机高度
			int height = r.nextInt(image.getHeight() - (g.getFontMetrics().getHeight() / 2 + 5)) + (g.getFontMetrics().getHeight() / 2 + 5);
			// int width = g.getFontMetrics().charWidth(0);
			g.drawString(str, i * (WIDTH / LENGTH), height);
			// g.drawString(str, i * width + 5, height);
			sb.append(str);// 将字符保存，存入Session

		}
		// 画干扰线
		for (int i = 0; i < LINES; i++) {
			g.setColor(getRandomColor());
			g.drawLine(r.nextInt(WIDTH + 1), r.nextInt(HEIGHT + 1), r.nextInt(WIDTH + 1), r.nextInt(HEIGHT + 1));
		}
		// 画噪音点(干扰点)
		for (int i = 0; i < POINT; i++) {
			g.setColor(getRandomColor());
			int x = r.nextInt(WIDTH + 1);
			int y = r.nextInt(HEIGHT + 1);
			g.drawLine(x, y, x, y);
		}
		Map<String, BufferedImage> map = new HashMap<String, BufferedImage>();
		map.put(sb.toString(), image);
		return map;
	}

	private static Color getRandomColor() {// 随机颜色
		int R = r.nextInt(256);
		int G = r.nextInt(256);
		int B = r.nextInt(256);
		return new Color(R, G, B);
	}

	private static Color getRandomColorB() {// 随机颜色
		int R = r.nextInt(128);
		int G = r.nextInt(128);
		int B = r.nextInt(128);
		return new Color(R, G, B);
	}

	private static Color getRandomColorC() {// 随机颜色
		int R = r.nextInt(128) + 128;
		int G = r.nextInt(128) + 128;
		int B = r.nextInt(128) + 128;
		return new Color(R, G, B);
	}

}